package com.artron.mediaartron.ui.fragment.shoppingcart;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.artron.baselib.adapter.recyclerview.BaseViewHolder;
import com.artron.baselib.adapter.recyclerview.DividerItemDecoration;
import com.artron.baselib.adapter.recyclerview.LoadMoreWrapper;
import com.artron.baselib.base.BaseLoadingFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.ui.LoadingPage;
import com.artron.baselib.utils.ToastUtil;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.ShoppingCartData;
import com.artron.mediaartron.data.entity.ShoppingCartItemData;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.ui.activity.GeneralActivity;
import com.artron.mediaartron.ui.adapter.ShoppingCartAdapter;
import com.artron.mediaartron.ui.adapter.LoadMoreListener;
import com.artron.mediaartron.ui.fragment.dialog.NormalDialogFragment;
import com.artron.mediaartron.ui.fragment.home.MainFragment;
import com.artron.mediaartron.util.TextSpanUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import butterknife.BindView;
import rx.Observable;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;

import static com.umeng.analytics.pro.x.I;
import static com.umeng.analytics.pro.x.o;


/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-10-31.
 */

public class ShoppingCartFragment extends BaseLoadingFragment<ShoppingCartData> implements View.OnClickListener {

    @BindView(R.id.ShoppingCartFragment_recycler)
    protected RecyclerView mRecyclerView;
    @BindView(R.id.ShoppingCartFragment_refresh)
    protected SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.ShoppingCartFragment_cb_all)
    protected CheckBox mCbAll;
    @BindView(R.id.ShoppingCartFragment_tv_all_price)
    protected TextView mTvAllPrice;
    @BindView(R.id.ShoppingCartFragment_btn_account)
    protected Button mBtnAccount;
    private List<ShoppingCartItemData> mData;
    private LoadMoreWrapper mWrapper;
    private ShoppingCartAdapter mAdapter;
    private ClassicsHeader mRefreshHeader;

    public static ShoppingCartFragment newInstance() {
        Bundle args = new Bundle();
        ShoppingCartFragment fragment = new ShoppingCartFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_shopping_cart;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        show();
        setHasOptionsMenu(true);
    }

    @Override
    protected void initVariable() {
        mRefreshHeader = new ClassicsHeader(getContext());
    }

    @Override
    protected void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext,
                LinearLayoutManager.VERTICAL, false));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext,
                DividerItemDecoration.VERTICAL_LIST, R.drawable.shape_rectangle_line_e3));
    }

    @Override
    public void initViewWithData(ShoppingCartData data) {
        updateShoppingCartNum();
        if (data!= null) {
            mData = data.getTrolleyDetailList();
        }

        filterData();
        mRefreshLayout.finishRefresh();

        mAdapter = new ShoppingCartAdapter(mContext, mData);
        mWrapper = new LoadMoreWrapper(mAdapter);
        mWrapper.setLoadMoreView(R.layout.layout_loading_more);
        mWrapper.setOnLoadMoreListener(new LoadMoreListener<>(
                mData, mWrapper, new Func1<Integer, Observable<Response<ShoppingCartData>>>() {
            @Override
            public Observable<Response<ShoppingCartData>> call(Integer integer) {
                String passId = AppProfile.getUserInfo().getPassId();
                return RetrofitHelper.getOrderApi().queryShoppingList(passId, integer, 10);
            }
        }
        ));
        mRecyclerView.setAdapter(mWrapper);
        mAdapter.setOnPriceChangeListener(new ShoppingCartAdapter.OnPriceChangeListener() {
            @Override
            public void onPriceChanged(View view, BaseViewHolder holder, int position, int number) {
                ShoppingCartItemData itemData = mData.get(position);
                itemData.setQuantity(number);
                String passId = AppProfile.getUserInfo().getPassId();
                Observable<Response> api = RetrofitHelper.getOrderApi().updateCartItemNum(passId, itemData.getId(), number + "");
                RetrofitHelper.subscript(api, new Action1<Response>() {
                    @Override
                    public void call(Response response) {
                        Log.d(TAG, "call: " + response);
                    }
                });
                updatePrice();
            }

            @Override
            public void onCheckChanged(View view, BaseViewHolder holder, int position, boolean isCheck) {
                mData.get(position).setChecked(isCheck);
                updatePrice();
            }
        });

        mRefreshLayout.setRefreshHeader(mRefreshHeader);
        mRefreshLayout.setOnRefreshListener(new SimpleMultiPurposeListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                showImmediate();
            }
        });

        mBtnAccount.setOnClickListener(this);

        mCbAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton cb, boolean isChecked) {
                for (ShoppingCartItemData itemData : mData) {
                    itemData.setChecked(isChecked);
                }
                updatePrice();
                mWrapper.notifyDataSetChanged();
            }
        });
        setAllPriceValue(0);
        updatePrice();
    }

    @Override
    protected int getErrorViewId() {
        return R.layout.general_empty;
    }

    private void updatePrice() {
        int allPrice = 0;
        int allNum = 0;
        for (ShoppingCartItemData itemData : mData) {
            if (itemData.isChecked()) {
                allPrice += itemData.getPrice() * itemData.getQuantity();
                allNum += itemData.getQuantity();
            }
        }
        setAllPriceValue(allPrice);
        if (allNum != 0) {
            mBtnAccount.setText(String.format("去结算(%d)", allNum));
        } else {
            mBtnAccount.setText("去结算");
        }
    }

    private void setAllPriceValue(int allPrice) {
        TextSpanUtils.setTextWithSpan(mTvAllPrice,
                TextSpanUtils.TextSpan.holder("￥", new AbsoluteSizeSpan(12, true)),
                TextSpanUtils.TextSpan.holder(allPrice + ".", new AbsoluteSizeSpan(18, true)),
                TextSpanUtils.TextSpan.holder("00", new AbsoluteSizeSpan(12, true)));
    }

    @Override
    protected Observable<Response<ShoppingCartData>> retrofitData() {
        String passId = AppProfile.getUserInfo().getPassId();
        return RetrofitHelper.getOrderApi().queryShoppingList(passId, 1, 10);
    }

    @Override
    protected LoadingPage.LoadResult checkData(ShoppingCartData data) {
        if (data == null || data.getTrolleyDetailList() != null &&
                data.getTrolleyDetailList().size() == 0) {
            return LoadingPage.LoadResult.Empty;
        }
        return super.checkData(data);
    }

    private void filterData() {
        List<ShoppingCartItemData> list = new ArrayList<>();
        for (ItemType itemType : ItemType.values()) {
            filter(itemType, list);
        }
        mData.clear();
        mData.addAll(list);
    }

    private void filter(ItemType type, List<ShoppingCartItemData> list) {
        String code = type.getType();
        ShoppingCartItemData data = new ShoppingCartItemData();
        data.setTitle(type.name());
        list.add(data);
        boolean isRemoveType = true;
        for (ShoppingCartItemData itemData : mData) {
            if (itemData.getWorksTypeCode().equals(code)) {
                list.add(itemData);
                isRemoveType = false;
            }
        }
        if (isRemoveType) {
            list.remove(data);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ShoppingCartFragment_btn_account:
                productAccount();
                break;
        }
    }

    private void productAccount() {
        List<ShoppingCartItemData> list = new ArrayList<>();
        for (ShoppingCartItemData item : mData) {
            if (item.isChecked()) {
                list.add(item);
            }
        }
        if (list.size() != 0) {
            GeneralActivity.start(mContext, GeneralActivity.ORDER_FROM_SHOPPING_CART, "确认订单", list);
        }
    }

    private enum ItemType {
        框画("kuanghua"), 海报("haibao"), 旅行记("lvxingji"), 台历("taili"), 挂历("guali");

        private final String mType;

        ItemType(String type) {
            this.mType = type;
        }

        public String getType() {
            return mType;
        }
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        if (item.getItemId() == R.id.menu_delete) {
            if (isHaveChecked()) {
                NormalDialogFragment dialog = NormalDialogFragment.newInstance("确认删除", "删除", "取消");
                dialog.show(getChildFragmentManager(), dialog.getOurTag());
                dialog.setOnPositiveClickListener(new Action0() {
                    @Override
                    public void call() {
                        ListIterator<ShoppingCartItemData> iterator = mData.listIterator();
                        List<ShoppingCartItemData> removeList = new ArrayList<>();
                        while (iterator.hasNext()) {
                            ShoppingCartItemData next = iterator.next();
                            if (next.isChecked()) {
                                removeList.add(next);
                                iterator.remove();
                            }
                        }

                        if (removeList.size() != 0) {
                            StringBuilder sb = new StringBuilder();
                            for (ShoppingCartItemData itemData : removeList) {
                                int position = mAdapter.deleteItem(itemData);
                                sb.append(itemData.getId()).append(",");
                                mWrapper.notifyItemRemoved(position);
                            }

                            //更新多余的Title信息
                            StringBuilder sbTitle = new StringBuilder();
                            for (int i = 0; i < mData.size(); i++) {
                                ShoppingCartItemData itemData = mData.get(i);
                                if (!TextUtils.isEmpty(itemData.getTitle())) {
                                    if (i + 1 < mData.size()) {
                                        itemData = mData.get(i + 1);
                                        if (!TextUtils.isEmpty(itemData.getTitle())) {
                                            sbTitle.append(i).append(",");
                                        }
                                    } else {
                                        sbTitle.append(i).append(",");
                                    }
                                }
                            }
                            if (!TextUtils.isEmpty(sbTitle.toString())) {
                                String substring = sbTitle.reverse().substring(1);
                                String[] split = substring.split(",");
                                for (String s : split) {
                                    int position = Integer.parseInt(s);
                                    mAdapter.deleteItem(position);
                                    mWrapper.notifyItemRemoved(position);
                                    mData.remove(position);
                                }
                            }
                            //

                            String passId = AppProfile.getUserInfo().getPassId();
                            RetrofitHelper.subscript(RetrofitHelper.getHostApi().deleteShoppingCartItem(
                                    passId, sb.substring(0, sb.length() - 1)), new Action1<Response>() {
                                        @Override
                                        public void call(Response response) {
                                            updateShoppingCartNum();
                                        }
                                    }
                            );
                            updatePrice();
                            if (mData.size() == 0) {
                                showImmediate();
                            }
                        }
                    }
                });
            } else {
                ToastUtil.show("请选中商品");
            }

        }
        return super.onOptionsItemSelected(item);
    }

    private void updateShoppingCartNum() {
        Fragment parentFragment = getParentFragment();
        if (parentFragment != null) {
            if (parentFragment instanceof MainFragment) {
                ((MainFragment) parentFragment).initShoppingItemNum();
            } else {
                Fragment oldFragment = parentFragment.getParentFragment();
                if (oldFragment != null && oldFragment instanceof MainFragment) {
                    ((MainFragment) oldFragment).initShoppingItemNum();
                }
            }
        }
    }

    private boolean isHaveChecked() {
        if (mData == null || mData.size() == 0) {
            return false;
        }

        for (ShoppingCartItemData item : mData) {
            if (item.isChecked()) {
                return true;
            }
        }
        return false;
    }

}
